﻿Option Strict Off

Imports System.Linq
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Spreadsheet
Imports System.Text.RegularExpressions
Imports System.ServiceModel.Syndication
Imports System.Xml

Public Class PDC10ListMaker

#Region "Event Handlers"
  Private Sub BuildListButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BuildListButton.Click
    EnableUI(False)

    Dim html As String = ""

    Dim ls = BuildList(CatalogTextBox.Text)
    html = BuildHTML(ls)

    WebBrowser1.DocumentText = html
    CurrentSessionLabel.Text = ""

    EnableUI(True)

  End Sub

  Private Sub RSSListButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RSSListButton.Click
    EnableUI(False)

    Dim enclosureType As String = "WMV"
    If RSSWMVHighRadioButton.Checked Then
      enclosureType = "WMVHigh"
    ElseIf RSSWMVRadioButton.Checked Then
      enclosureType = "WMVLow"
    ElseIf RSSMP4RadioButton.Checked Then
      enclosureType = "MP4Low"
    ElseIf RSSMP4HighRadioButton.Checked Then
      enclosureType = "MP4High"
    Else
      enclosureType = "WMV"
    End If

    BuildRSSFiles(CatalogTextBox.Text, SaveRSSFilesPathTextbox.Text, RSSSaveFileNameTextBox.Text, enclosureType)

    EnableUI(True)

  End Sub
  Private Sub CopyLinkLabel_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles CopyLinkLabel.LinkClicked

    If WebBrowser1.DocumentText.Length > 0 Then
      My.Computer.Clipboard.SetText(WebBrowser1.DocumentText.Replace("<html><body>", "").Replace("</body></html>", ""))
    End If

  End Sub

#End Region


  Private Sub BuildRSSFiles(ByVal CatalogURL As String, ByVal savePath As String, ByVal saveFileName As String, ByVal enclosuretype As String)
  
    Dim ls = BuildList(CatalogURL)

    Dim feed As SyndicationFeed = New SyndicationFeed("Greg's PDC10 Video Session List - " & enclosuretype,
                                                      "PDC10",
                                                      New Uri("http://microsoftpdc.com/"),
                                                      "PDC10-" & enclosuretype,
                                                      DateTime.Now)

    'feed.ImageUrl = New Uri("http://microsoftpdc.com/content/images/creative/PDC09Bling_General_ThreadsConnected_136.jpg")

    Dim items As List(Of SyndicationItem) = New List(Of SyndicationItem)()

    For Each s In ls
      Dim resoureURL As String = ""
      Dim mimetype As String = ""
      Dim WMVHighURL As String = ""
      Dim WMVURL As String = ""
      Dim MP4High As String = ""
      Dim MP4Low As String = ""

      For Each d In s.Downloads

        If d.Item2.EndsWith("wmv") Then
          If d.Item2.Contains("High") Then
            WMVHighURL = d.Item2
          Else
            WMVURL = d.Item2
          End If
        ElseIf d.Item2.EndsWith("mp4") Then
          If d.Item2.Contains("High") Then
            MP4High = d.Item2
          Else
            MP4Low = d.Item2
          End If

        End If

      Next

      Select Case enclosuretype.ToUpper
        Case "WMVHIGH"
          resoureURL = WMVHighURL
          mimetype = "video/x-ms-wmv"
        Case "WMVLOW"
          resoureURL = WMVURL
          mimetype = "video/x-ms-wmv"
        Case "MP4LOW"
          resoureURL = MP4Low
          mimetype = "video/mp4"
        Case "MP4HIGH"
          resoureURL = MP4High
          mimetype = "video/mp4"

      End Select

      If resoureURL.Length > 0 Then

        Dim item As SyndicationItem = New SyndicationItem(s.Code & " " & s.Title, s.Description, New Uri(s.AlternateCode), s.Code, s.SessionDTTM)
        item.PublishDate = s.SessionDTTM

        item.ElementExtensions.Add(<enclosure url=<%= resoureURL %> length="0" type=<%= mimetype %>/>)

        items.Add(item)

      End If

    Next

    feed.Items = items
    If IO.Directory.Exists(savePath) = False Then
      IO.Directory.CreateDirectory(savePath)
    End If
    Dim rssWriter As XmlWriter = XmlWriter.Create(IO.Path.Combine(savePath, saveFileName))
    Dim rssFormatter As Rss20FeedFormatter = New Rss20FeedFormatter(feed)
    rssFormatter.WriteTo(rssWriter)
    rssWriter.Close()
  End Sub

  Private Sub EnableUI(ByVal enable As Boolean)
    CatalogTextBox.Enabled = enable

    BuildListButton.Enabled = enable

    VerifyLinkCheckBox.Enabled = enable
    WMVCheckBox.Enabled = enable
    WMVHQCheckBox.Enabled = enable
    ZuneCheckBox.Enabled = enable
    MP4CheckBox.Enabled = enable
    ZIPCheckBox.Enabled = enable
    PPTXCheckBox.Enabled = enable
    CopyLinkLabel.Enabled = enable
    TabControl1.Enabled = enable

  End Sub

  Private Function BuildList(ByVal CatalogURL As String) As Generic.List(Of Session)

    Dim svc = New PDC10OData.ScheduleModel(New Uri(CatalogURL))

    Dim sessions = From session In svc.Sessions.Expand("DownloadableContent").ToList 'Where session.Code = "FT03"
    Dim timeslots = From session In svc.TimeSlots.ToList

    Dim ls = New Generic.List(Of Session)

    For Each s In sessions
      Debug.Print(s.FullTitle)
      Dim title = s.ShortTitle
      Dim code = s.Code
      Dim description = s.ShortDescription
      Dim sessiondate As Date

      If s.TimeSlotId <> Guid.Empty Then
        Dim times = From t In timeslots Where t.Id = s.TimeSlotId Select t

        sessiondate = times.First.Start

      Else
        sessiondate = New Date(2010, 10, 27, 8, 0, 0)
      End If

      Dim alternateCode = s.ShortUrl
      Dim alternateSessionCode = s.ShortUrl

      If String.IsNullOrEmpty(alternateCode) Then
        alternateCode = ""
      End If

      If String.IsNullOrEmpty(alternateSessionCode) Then
        alternateSessionCode = ""
      End If
      Dim sess = New Session() With {.Code = code, .Title = title,
                                    .Description = description, .SessionDTTM = sessiondate,
                                    .AlternateCode = alternateCode, .AlternateSessionCode = alternateSessionCode}


      For Each d In s.DownloadableContent
        Debug.Print(d.Title + " " + d.Url + "[END]")
        sess.Downloads.Add(New Tuple(Of String, String)(d.Title, d.Url))
      Next

      ls.Add(sess)

    Next

    Return ls

  End Function


  Private Function BuildHTML(ByVal ls As Generic.List(Of Session)) As String
    Dim q = From link In ls Order By link.SortTitle
    Dim sb = New System.Text.StringBuilder
    sb.Append("<html><body>")
    sb.Append("<table>")
    sb.Append(GetHeader())

    For Each link As Session In q
      sb.Append("<tr>")

      CurrentSessionLabel.Text = link.Code
      CurrentSessionLabel.Refresh()

      If Not link.Code.Contains("-R") Then
        sb.Append("<td>")
        sb.Append(GetTitle(link.SortTitle, link.Code, link.AlternateSessionCode, VerifyLinkCheckBox.Checked))

        sb.Append("</td>")
        sb.AppendLine(GetVideoLinks(link, VerifyLinkCheckBox.Checked))
      End If

      sb.Append("</tr>")

    Next
    sb.Append("</table>")

    sb.Append("</body></html>")


    Return sb.ToString
  End Function

  Private Function PageExists(ByVal URL As String, ByVal verifyLink As Boolean) As Boolean

    Return PageVerify.PageExists(URL, verifyLink)

  End Function

  Private Function GetTitle(ByVal title As String, ByVal code As String, ByVal alternateSessionCode As String, ByVal verifyLink As Boolean) As String
    Dim sb As New System.Text.StringBuilder

    Dim url = alternateSessionCode

    If PageExists(url, False) Then
      sb.Append("<a href=")
      sb.Append(Chr(34))
      sb.Append(url)
      sb.Append(Chr(34))
      sb.Append(">")
      sb.Append(title)
      sb.Append("</a>")
    Else
      sb.Append(title)
    End If

    Return sb.ToString

  End Function

  Private Function GetVideoLinks(ByVal session As Session, ByVal verifyLink As Boolean) As String
    Dim sb = New System.Text.StringBuilder

    Dim WMVHighURL As String = ""
    Dim WMVURL As String = ""
    Dim PPTXURL As String = ""
    Dim MP4High As String = ""
    Dim MP4Low As String = ""

    For Each s In session.Downloads

      If s.Item2.Trim.EndsWith("wmv") Then
        If s.Item2.Contains("High") Then
          WMVHighURL = s.Item2
        Else
          WMVURL = s.Item2
        End If
      ElseIf s.Item2.Trim.EndsWith("pptx") Then
        PPTXURL = s.Item2
      ElseIf s.Item2.Trim.EndsWith("mp4") Then
        If s.Item2.Contains("High") Then
          MP4High = s.Item2
        Else
          MP4Low = s.Item2
        End If

      End If

    Next


    If WMVHQCheckBox.Checked Then
      sb.AppendLine(GetResourceLink(WMVHighURL, "WMVHIGH", verifyLink))
    End If
    If WMVCheckBox.Checked Then
      sb.AppendLine(GetResourceLink(WMVURL, "WMV", verifyLink))
    End If
    If ZuneCheckBox.Checked Then
      sb.AppendLine(GetResourceLink(MP4Low, "MP4Low", verifyLink))
    End If
    If MP4CheckBox.Checked Then
      sb.AppendLine(GetResourceLink(MP4High, "MP4High", verifyLink))
    End If
    'If ZIPCheckBox.Checked Then
    '  sb.AppendLine(GetResourceLink(URL_Prefix & "zip/", code, "zip", "ZIP", verifyLink))
    'End If
    If PPTXCheckBox.Checked Then
      sb.AppendLine(GetResourceLink(PPTXURL, "PPTX", verifyLink))
    End If

    Return sb.ToString
  End Function

  Private Function GetHeader() As String
    Dim sb = New System.Text.StringBuilder

    sb.Append("<thead>")
    sb.Append("<tr>")
    sb.Append("<th width=0>")
    sb.Append("Title")
    sb.Append("</th>")
    If WMVHQCheckBox.Checked Then
      sb.Append("<th width=75>")
      sb.Append("WMV High")
      sb.Append("</th>")
    End If
    If WMVCheckBox.Checked Then
      sb.Append("<th>")
      sb.Append("WMV Low")
      sb.Append("</th>")
    End If
    If ZuneCheckBox.Checked Then
      sb.Append("<th>")
      sb.Append("MP4 Low")
      sb.Append("</th>")
    End If
    If MP4CheckBox.Checked Then
      sb.Append("<th>")
      sb.Append("MP4 High")
      sb.Append("</th>")
    End If
    If ZIPCheckBox.Checked Then
      sb.Append("<th>")
      sb.Append("ZIP")
      sb.Append("</th>")
    End If
    If PPTXCheckBox.Checked Then
      sb.Append("<th>")
      sb.Append("PPTX")
      sb.Append("</th>")
    End If


    sb.Append("</tr>")
    sb.Append("</thead>")

    Return sb.ToString

  End Function
  Private Function GetResourceLink(ByVal URL As String, ByVal name As String, ByVal verifyLink As Boolean) As String
    Dim sb = New System.Text.StringBuilder
    Dim finalurl As String = URL
    Dim addlink As Boolean

    If finalurl.Length > 0 Then
      addlink = True
    Else
      addlink = False
    End If

    sb.Append("<td>")

    If addlink Then
      sb.Append("<a href=")
      sb.Append(Chr(34))
      sb.Append(finalurl)
      sb.Append(Chr(34))
      sb.Append(">")
      sb.Append(name)
      sb.Append("</a>")

    Else
      sb.Append("&nbsp")
    End If
    sb.Append("</td>")

    Return sb.ToString


  End Function


End Class